<template>
  <router-view></router-view>
</template>
<script setup lang="ts">
import { onMounted } from 'vue'
// 20240805改了store
// import { useStore } from 'vuex'
import store from '@/render/store/index'
import { useRoute, useRouter } from 'vue-router'
import { get as _get } from 'lodash-es'

import { noLoginGet as getPublishedSurveyInfo } from '@/management/api/dataform'
import { checkHasPurview } from '@/management/api/dataform-extend'
import useCommandComponent from '@/render/hooks/useCommandComponent'

import AlertDialog from '@/render/components/AlertDialog.vue'
import { initRuleEngine } from '@/render/hooks/useRuleEngine.js'
import LoginDialog from '@/render/components/LoginDialog.vue'

// const store = useStore()
const route = useRoute()
const router = useRouter()

const loadData = (res: any, surveyPath: string) => {
  if (res?.result?.formId) {
    const { dataFormAttributeList } = res.result
    const schema = res.result.skinConf ? JSON.parse(res.result.skinConf) : {}

    const bannerConf = _get(schema, 'bannerConf', {
      "titleConfig": {
        "mainTitle": res.result.formRemark || "",
        "subTitle": res.result.formName || ""
      },
      "bannerConfig": {
        "bgImage": "",
        "videoLink": "",
        "postImg": ""
      }
    })
    const bottomConf = _get(schema, 'bottomConf', {
      "logoImage": "",
      "logoImageWidth": "60%"
    })
    const baseConf = _get(schema, 'baseConf', {
      "begTime": res.result.startTime,
      "endTime": res.result.endTime,
      "tLimit": 0,
      "answerLimitTime": 0,
      "isMultiple": true,
      "anonymous": true,
      "isUpdate": true,
      "isDel": true,
      "isTop": true,
      "language": "chinese",
      "answerBegTime": "00:00:00",
      "answerEndTime": "23:59:59",
      "answerUser": [],
      "adminUser": []
    })
    const skinConf = _get(schema, 'skinConf', {
      "skinColor": "#4a4c5b",
      "inputBgColor": "#ffffff",
      "backgroundConf": {
        "color": "#fff"
      },
      "themeConf": {
        "color": "#0081fa"
      },
      "contentConf": {
        "opacity": 100
      }
    })
    const submitConf = _get(schema, 'submitConf', {
      "submitTitle": "提交",
      "confirmAgain": {
        "is_again": false,
        "again_text": "确认要提交吗？"
      },
      "msgContent": {
        "msg_200": "提交成功",
        "msg_9001": "您来晚了，感谢支持问卷~",
        "msg_9002": "请勿多次提交！",
        "msg_9003": "您来晚了，已经满额！",
        "msg_9004": "提交失败！"
      }
    })
    const logicConf = _get(schema, 'logicConf', {
      "showLogicConf": []
    }) 
    const dataConf = _get(schema, 'dataConf', {
        "dataList": []
      })

    const metaData = {
      ...res.result,
      skinConf: '',
      "_id": res.result.formId,
      "createDate": res.result.createTime,
      "updateDate": res.result.lastModifyTime,
      "title": res.result.formName || '调研活动',
      "remark": res.result.formRemark,
      "surveyType": res.result.formType,
      "surveyPath": res.result.formId,
      "creatorName": res.result.creatorName || 'admin',
      "owner": res.result.creatorName || 'admin',
      "ownerId": res.result.creatorId,
      "createMethod": "basic",
      "currentUserId": res.result.creatorId,
      "isCollaborated": false
    }

    let dataList: any = []
    console.log('dataConf', dataConf)
    dataFormAttributeList.forEach((item: any) => {
      let fields = item.attrContent ? JSON.parse(item.attrContent) : {}
      dataList.push({
        ...item,
        ...fields,
        field: item.attrId
      })
    })

    let cf = {
      dataList: dataList
    }
    console.log('cf', cf)
    const questionData = {
      metaData,
      bannerConf,
      baseConf,
      bottomConf,
      dataConf: cf,
      skinConf,
      submitConf
    }

    document.title = res.result.formName 

    console.log('questionData', questionData)
    store.commit('setSurveyPath', surveyPath)
    store.dispatch('init', questionData)
    initRuleEngine(logicConf?.showLogicConf)

    if (!baseConf?.anonymous && !(window as any).$app?.user?.token) {
      const needlogin = useCommandComponent(LoginDialog)
      needlogin({ visible: true })
    } 
    if (!baseConf?.anonymous && (window as any).$app?.user?.token) {
      checkHasPurview({ formId: surveyPath, objectId: (window as any).$app?.user?.userId, useLimit: metaData.useLimit || '2' }).then((resp: any) => {
        console.log('resp', resp)
        if (resp?.result !== '1') {
          router.push({ name: 'previewErrorPage' })
          store.commit('setErrorInfo', {
            errorType: 'overTime',
            errorMsg: '您不在填写人员名单中，请联系管理员添加~'
          })
        }
      })
    }
  } else {
    throw new Error(res?.serverResult?.resultMessage || '活动不存在')
  }
}
onMounted(() => {
  const formId = route.params.id || route.meta?.id
  store.commit('setSurveyPath', formId)
  getDetail(formId as string)
})

const getDetail = async (surveyPath: string) => {
  const alert = useCommandComponent(AlertDialog)

  try {
    const res: any = await getPublishedSurveyInfo(surveyPath)
    loadData(res, surveyPath)
  } catch (error: any) {
    console.log(error)
    alert({ title: error.message || '获取活动失败' })
  }
}
</script>
